package controllers
{
	import models.DebuggerHistoryEntry;
	import models.State;
	import models.Variable;
	
	import mx.collections.ArrayCollection;
	import mx.core.Application;

	public class HistoryController extends Object
	{
		public function HistoryController()
		{
			super();
		}
		
		public function cacheState(state:State):void{
			Application.application.stateHistory[state.id] = state;
		}
		
		public function getStateFromCache(stateID:Number):State{
			return Application.application.stateHistory[stateID];
		}
		
		public function cacheVariable(stateID:Number, variable:Variable):void{
			// Format the variable name, put "global_" or "_local" as prefix
			var variableKey:String = variable.scope + "_" + variable.name;
			
			// Get the history array of the variable
			var history:Array;
			if(variableKey in Application.application.variableHistory)
				history = Application.application.variableHistory[variableKey];
			else{
				history = new Array();
				Application.application.variableHistory[variableKey] = history;
			}
			
			history[stateID] = {stateID: stateID, value: variable.value};
			
			// Update all views if the variable is the selected variable
			if(Application.application.selectedVariable == variable)
				updateSelectedVariableHistory();
		}
		
		public function getVariableHistory(variable:Variable):Array{
			// Format the variable name, put "global_" or "_local" as prefix
			var variableKey:String = variable.scope + "_" + variable.name;		
			
			return Application.application.variableHistory[variableKey];
		}
		
		public function updateSelectedVariableHistory():void{
			var history:Array = getVariableHistory(Application.application.selectedVariable);
			if(!history)
				history = new Array();
			// Fill the binded ArrayCollection, so that we filter out the blank states
			Application.application.selectedVariableHistory.removeAll();
			for(var i:uint=0;i<history.length;i++){
				var entry:Object = history[i];
				if(entry)
					Application.application.selectedVariableHistory.addItem(entry);
			} 			
		}
		
		public function showVariableHistory(variable:Variable):void{
			Application.application.selectedVariable = variable;
			updateSelectedVariableHistory();
			
			Application.application.mainView.mainViewStack.selectedChild = Application.application.mainView.variableHistoryView;
		}
		
		// Add a debugger history entry
		public function addDebuggerHistoryEntry(entry:DebuggerHistoryEntry):void{
			Application.application.debuggerHistory.addItem(entry);
		}
		
	}
}